package www.dashu.com.controller;

import www.dashu.com.api.CommonResult;
import www.dashu.com.service.RedisService;
import www.dashu.com.domain.SysPermission;
import www.dashu.com.dto.PermissionQuery;
import www.dashu.com.service.SysPermissionService;
import www.dashu.com.service.SysRolePermsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@Api(tags = "SysPermissionController", description = "权限管理")
@RequestMapping("/permission")
public class SysPermissionController
{

    @Autowired
    SysPermissionService permissionService;
    @Autowired
    SysRolePermsService rolePermsService;

    @Autowired
    RedisService redisService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @ApiOperation(value = "权限列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Page<SysPermission>> list(PermissionQuery permissionQuery) {

        try {
            Page<SysPermission> pageData = permissionService.findAll(permissionQuery);
            return CommonResult.success(pageData);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @ApiOperation(value = "新增权限")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult create(@RequestBody SysPermission permission) {
        permission.setId(permissionService.createId(permission));
        permission.setCreateTime(new Date());
        permission.setUpdateTime(new Date());
        permissionService.save(permission);
        permissionService.initResourceRolesMap();
        return CommonResult.success();
    }

    @ApiOperation(value = "修改权限")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult update(@RequestBody SysPermission permission) {
        permission.setUpdateTime(new Date());
        permissionService.save(permission);
        permissionService.initResourceRolesMap();
        return CommonResult.success();
    }

    @ApiOperation(value = "删除权限")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public CommonResult delete(@RequestBody SysPermission permission) {
        permissionService.deleteById(permission.getId());
        rolePermsService.deleteSysRolePermsByPermId(permission.getId());
        permissionService.initResourceRolesMap();
        return CommonResult.success();
    }

    @ApiOperation(value = "权限树")
    @RequestMapping(value = "/tree", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Map<String, Object>> tree(@RequestBody Map<String,List<String>> params) {
        Map<String, Object> ret = new HashMap<>();
        List<SysPermission> permissionList = permissionService.findAllSort();
        List<SysPermission> treeRoot = new ArrayList<>();
        Map<Long,SysPermission> permissionMap = new HashMap<>();
        permissionList.forEach(item -> {
            permissionMap.put(item.getId(), item);
        });

        permissionList.forEach(item -> {
            Long pid = item.getPid();
            SysPermission parent = permissionMap.get(pid);
            if(null == parent){
                treeRoot.add(item);
            }else {
                List<SysPermission> children = parent.getChildren();
                if(null == children){
                    children = new ArrayList<>();
                }
                children.add(item);
                parent.setChildren(children);
            }
        });
        List<Long> rolePerms = new ArrayList<>();
        if(!StringUtils.isEmpty(params)){
            rolePerms = rolePermsService.findSysRolePermsByRoleIds(params.get("roleId"));
//            perms = rolePerms.stream().filter(item -> item.getPType() == 1).map(item -> item.getPId()).collect(Collectors.toList());
        }
        ret.put("tree", treeRoot);
        ret.put("perms", rolePerms);
        return CommonResult.success(ret);
    }

}
